<template>
  <a-slider
    :value="fakeValue"
    v-bind="$attrs"
    :range="range"
    :min="min"
    :max="max"
    @change="onChange"
  />
</template>
<script>
export default {
  // 继承
  name: 'SSlider',
  props: {
    modelValue: {
      type: String || Number,
      required: false
    },
    range: {
      type: Boolean,
      required: false,
      default: false
    },
    separator: {
      type: String,
      required: false,
      default: '-'
    },
    min: {
      type: Number,
      required: false,
      default: 0
    },
    max: {
      type: Number,
      required: false,
      default: 100
    }
  },
  emits: ['change', 'update:modelValue'],
  data() {
    return {
      fakeValue: this.initValue()
    }
  },
  watch: {
    modelValue(val) {
      this.fakeValue = this.initValue()
    }
  },
  methods: {
    initValue() {
      let val = this.modelValue
      if (val != null) {
        if (this.range) {
          const array = val.split(this.separator)
          array[0] = Number.parseInt(array[0])
          array[1] = Number.parseInt(array[1])
          this.fakeValue = array
        } else {
          if (typeof val === 'number') {
            this.fakeValue = val
          } else {
            this.fakeValue = Number.parseInt(val)
          }
        }
      } else {
        if (this.range) {
          this.fakeValue = [this.min, this.max]
        } else {
          this.fakeValue = this.min
        }
      }
    },
    onChange(e) {
      let val = e
      if (val != null) {
        if (Array.isArray(val)) {
          val = val[0] + this.separator + val[1]
        } else {
          val = val + ''
        }
      }
      this.$emit('update:modelValue', val)
      this.$emit('change', val)
    }
  }
}
</script>
